<template>
    <div style="padding: 12px; box-sizing: border-box;">

        <el-dialog v-model="dialogVisible" :title="formData.id ? '职务修改' : '职务新增'" width="500">
            <div style="height: 350px;overflow-y: scroll;">
                <el-form :inline="false" :model="formData">
                    <el-form-item label="职务名称">
                        <el-input style="width: 600px;" v-model="formData.name" placeholder="职务名称" clearable />
                    </el-form-item>


                    <el-form-item label="职务权限">
                        <el-cascader style="width: 600px;" v-model="formData.roles" :options="dtableData"
                            placeholder="职务权限" :props="props" @change="handleChange" />
                    </el-form-item>

                    <el-form-item label="按钮权限">

                        <template v-if="btnroleList.length != 0">
                            <div v-for="e in btnroleList" :key="e.name" style="display: flex;align-items: center;width:100%;border-bottom:1px solid #8b8b8b">

                                <div style="margin-right: 10px;display:flex;flex-shrink:0;color:#409eff;font-weight:600;cursor:pointer" @click='chooseAll(e)'>{{ e.alias }}:</div>
                                <el-checkbox-group v-model="e.checkList">
                                    <el-checkbox v-for="es in e.btnRoles" :label="es.name" :key="es.name"
                                        :value="e.name + es.code" />
                                </el-checkbox-group>
                            </div>
                        </template>
                        <template v-else>
                            <span style="font-size: 12px;">所选菜单暂无按钮权限</span>
                        </template>

                    </el-form-item>
                    <el-form-item label="是否禁用">
                        <el-radio-group v-model="formData.disabled">
                            <el-radio :value="true" size="large">是</el-radio>
                            <el-radio :value="false" size="large">否</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="职务次序">
                        <el-input-number v-model="formData.order" :min="0" clearable />

                    </el-form-item>



                </el-form>
            </div>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button @click="onSubmit" type="primary">
                        确定
                    </el-button>
                </div>
            </template>
        </el-dialog>

        <el-card style="width: 100%;">
            <template #header>
                <div style="display: flex;align-items: center;justify-content: space-between;">
                    <span>职务列表</span>
                    <el-button @click="handleForm()" type="primary">新增</el-button>
                </div>
            </template>
            <el-table :data="tableData" style="width: 100%; margin-bottom: 20px" row-key="_id" border>

                <el-table-column align="center" prop="name" label="职务名称" />
                <el-table-column align="center" prop="roles" label="职务权限">
                    <template #default="scope">
                        <el-space wrap>
                            <el-tag :key="ei" v-for="(es, ei) in scope.row.roles.map((e: any) => e.alias)">
                                {{ es }}
                            </el-tag>
                        </el-space>
                    </template>
                </el-table-column>
                <el-table-column align="center" prop="disabled" label="是否禁用">
                    <template #default="scope">
                        <el-tag v-if="!scope.row.disabled" type="success">未禁用</el-tag>
                        <el-tag v-else type="danger">已禁用</el-tag>
                    </template>

                </el-table-column>
                <el-table-column align="center" prop="order" label="次序" />
                <el-table-column align="center" label="操作">
                    <template #default="scope">
                        <el-space wrap>
                            <el-button size="small" @click="handleForm(scope.row._id)" type="primary">编辑</el-button>
                            <el-button size="small" @click="deletem(scope.row._id)" type="danger">删除</el-button>
                        </el-space>
                    </template>


                </el-table-column>
            </el-table>
            <template #footer>
                <div style="display: flex;justify-content: center;">
                    <el-pagination v-model:current-page="pagination.page" :page-size="pagination.size" background
                        layout="total, prev, pager, next" :total="pagination.total" @size-change="handleSizeChange"
                        @current-change="handleCurrentChange" />
                </div>
            </template>
        </el-card>
        <sDialog ref="sdialog" :content="scontent" :confirmFunction="confirmFunction"></sDialog>
    </div>
</template>

<script setup lang="ts">
import { ref, getCurrentInstance } from "vue"
import { resetAble } from "@/composable/reset"
import { ElMessage } from "element-plus";
import { addrole, rolelist, delrole, putrole } from "@/api/role";
import { getmenu, getrolei, } from "@/api/menu";
import { Igetotherrole } from "@/utils/getroles";
import sDialog from "@/components/sDialog.vue";
const { proxy } = getCurrentInstance() as any
const tableData = ref([])
const dtableData = ref([])
const dialogVisible = ref(false)
const pagination = ref({
    page: 1,
    size: 10,
    total: 0
})

const handleForm = async (id?: string) => {

    reset()
    if (id) {
        let res = await getrolei({ id })
        if (res) {
            formData.value = res.data
            formData.value.id = id
            btnfilter(formData.value.roles)
            let {  btnrole } = (await Igetotherrole(id)) as any;
            btnroleList.value = btnroleList.value.map((e: any) => {
                e.checkList = [...new Set( btnrole)].filter(t => e.btnRoles.map((ts: any) => e.name + ts.code).includes(t))
                return e
            })
        }


    } else {


    }
    dialogVisible.value = true
}

const handleSizeChange = () => {

}

const handleCurrentChange = () => {

}
const { data: formData, reset } = resetAble({
    name: '',
    roles: [],
    disabled: false,
    order: 0,
    id: "",
    btnroles: []
})
const handleItemId = ref('')
const scontent = ref('')
const confirmFunction = async () => {
    let res = await delrole({ id: handleItemId.value })
    if (res) {
        ElMessage({
            message: '操作成功',
            grouping: true,
            type: 'success',
        })
        init()
    }
}

const chooseAll=(e:any)=>{
 
    e.checkList=e.checkList?e.checkList.length==0?e.btnRoles.map((es:any)=>e.name+es.code):[] : e.btnRoles.map((es:any)=>e.name+es.code)

}

const deletem = async (id: string) => {
    handleItemId.value = id
    scontent.value = '确定删除吗?'
    proxy.$refs.sdialog.showCenterDialog = true

}
const props = ref({
    value: '_id',
    label: 'alias',
    emitPath: false,
    multiple: true,
    checkStrictly: false,
})
const onSubmit = async () => {
    formData.value.btnroles = [...new Set(btnroleList.value.map((e: any) => e.checkList).flat())] as any
    if (formData.value.id) {
        let res = await putrole(formData.value) as any
        if (res) {
            init()

            ElMessage({
                message: '操作成功',
                grouping: true,
                type: 'success',
            })
        }
    } else {
        let res = await addrole(formData.value) as any
        if (res) {
            init()

            ElMessage({
                message: '操作成功',
                grouping: true,
                type: 'success',
            })
        }
    }

    dialogVisible.value = false
}

const btnfilter = (arr: any) => {
    btnroleList.value = allList.value && allList.value.filter((e: any) => !e.isMenu).filter((e: any) => e.btnRoles && e.btnRoles.length != 0)
    btnroleList.value = btnroleList.value.filter((e: any) => arr.includes(e._id))

}

const handleChange = (e: any) => {
    btnfilter(e)
}

const flattenTree = (data: any, ancestors: any = [], flatArray: any = []) => {
    // 如果传入的是单个对象，则放入数组中处理
    if (!Array.isArray(data)) {
        data = [data];
    }

    data.forEach((item: any) => {
        // 创建新的项以避免修改原始数据
        const newItem = { ...item } as any;

        // 添加或更新 ancestors 字段
        newItem.ancestors = [...ancestors, item.name];

        // 将当前项添加到扁平数组中
        flatArray.push(newItem);

        // 递归处理子节点
        if (Array.isArray(item.children) && item.children.length > 0) {
            flattenTree(item.children, newItem.ancestors, flatArray);
        }
    });

    return flatArray;
}

const btnroleList = ref<any>([])
const allList = ref([])
const init = async () => {
    let res = await rolelist()
    if (res) {
        tableData.value = res.data
    }
    let ress = await getmenu()
    if (ress) {
        dtableData.value = ress.data
        allList.value = flattenTree(dtableData.value)

    }

}

init()
</script>
